import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import store from '@/store'
import { openToast } from '@/assets/js/tools'
import { xml2json, getXMLStr } from '@/assets/js/xml2json'
/**
 * axios 版本
 */
export function request (params) {
  let requestData = {}

  let headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'
  }

  if (params.method === 'post') {
    if (params.type === 'XML') {
      headers.SOAPAction = 'vanke2018'
      headers['Content-type'] = 'text/xml;charset=UTF-8'
      requestData = getXMLStr(params.data)
      // console.log('XML请求数据', requestData)
    } else if (params.type === 'formData') {
      requestData = new FormData()
      for (let index in params.data) {
        requestData.append(index, params.data[index])
      }
      headers['Content-type'] = 'application/form-data;charset=utf-8'
    } else {
      requestData = qs.stringify(params.data)
    }
  } else {
    // headers['Content-type'] = 'application/json;charset=utf-8'
  }

  if (params.url.indexOf('ormrpc') !== -1) {
    // console.log('<金蝶接口>')
    if (store.state.sessionID) params.data.sessionID = store.state.sessionID
  }

  return new Promise((resolve, reject) => {
    store.commit('isLoading', true)
    axios({
      method: params.method ? params.method : 'get',
      url: params.url,
      data: requestData,
      timeout: 300 * 1000,
      // onUploadProgress: progressEvent => {
      //   // 对原生进度事件的处理
      //   console.log('up', progressEvent)
      // },
      // onDownloadProgress: progressEvent => {
      //   store.commit('isLoading', true)
      //   // console.log('down', progressEvent)
      //   // 对原生进度事件的处理
      // },
      params: params.method === 'post' ? {} : params.data,
      headers
    }).then(response => {
      store.commit('isLoading', false)
      if (response.status === 200) {
        // console.log(response.data)
        if (params.type === 'XML') {
          let data = response.data
          let parser = new DOMParser()
          // xml字符串转换为XML对象
          let xmlobject = parser.parseFromString(data, 'text/xml')
          // console.log(xmlobject)
          // 复原转义的XML字符串
          let resXMLStr = xmlobject.getElementsByTagName('ImageInterfaceServiceReturn')[0].innerHTML
          resXMLStr = resXMLStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&apos;/g, "'")
          console.log('xml -> ', parser.parseFromString(resXMLStr, 'text/xml'))
          // 将xml字符串转换为json对象
          let resData = xml2json(parser.parseFromString(resXMLStr, 'text/xml'))
          console.log('response -> ', JSON.stringify(resData))
          if (+resData.root.result['#text'] === 0) {
            let item = resData.root.items.item
            resolve(item)
            if (+item.result['#text'] !== 0) {
              openToast({
                msg: item.errormsg['#text'],
                duration: 3000
              })
            }
          } else {
            openToast({
              msg: resData.root.errormsg['#text'] || '请求失败',
              duration: 3000
            })
            console.log('errormsg>>>>>', resData.root.errormsg['#text'])
          }
        } else {
          resolve(response.data)
          // 金蝶接口的公共错误提示
          if (params.url.indexOf('ormrpc') !== -1) {
            if (response.data.code !== 200) {
              openToast({
                msg: response.data.msg || '请求失败',
                duration: 3000
              })
            }
          }
        }
      } else {
        console.log(`请求失败 status: ${response.status}`)
        openToast({
          msg: `请求失败 status: ${response.status}`,
          duration: 1500
        })
      }
    }).catch(error => {
      store.commit('isLoading', false)
      if (error.response) {
        // 请求已发出，但服务器响应的状态码不在 2xx 范围内
        // console.log('data>>', error.response.data)
        console.log('status>>', error.response.status)
        // console.log('headers>>', error.response.headers)
        openToast({
          msg: `请求失败 status: ${error.response.status}`,
          duration: 1500
        })
      } else {
        console.log('Error', error.message)
        openToast({
          msg: `Error：${error.message}`,
          duration: 1500
        })
      }
      // console.log(error.config)
      if (reject) return reject(error)
    })
  })
}

Vue.use({
  install: () => {
    Vue.prototype.$http = request
  }
})
